package procedureandconsumer;

public class MyStack {
    //属性
    private Object[] stack;
    //栈的元素个数
    private int len;
    //栈顶元素指针位置
    private int index;

    public MyStack(int len) {
        this.len = len;
        //初始化栈的数组
        stack = new Object[len];
        //栈顶元素初识位置
        this.index = 0;
    }

    /**
     * 入栈
     * @param obj
     */
    public synchronized void push(Object obj){
        //入栈操作
        //仓库满了
        if(index>=len){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //存入元素
        stack[index] = obj;
        index++;
        this.notifyAll();
    }
    /**
     * 出栈
     */
    public synchronized Object pop(){
        //仓库为空
        if(index<=0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        index--;
        Object obj=stack[index];
        stack[index]=null;
        this.notifyAll();
        return obj;
    }
}
